package control

import (
	"WeChatMGRA/modul"
	"WeChatMGRA/requests"
	"WeChatMGRA/server/smodul"
	"encoding/json"
	"gitee.com/yutiandou/wdtools/wdlog"
	"gitee.com/yutiandou/wdtools/wdsys"
	"gitee.com/yutiandou/wdtools/wdutil"
	"strconv"
)

var ReceiveInfo_chan = make(chan *modul.ReceiveInfo,10000)


func StartWorkPool(){
	_,cpuconut := wdsys.GetCpuPercent()
	for ;cpuconut>0;cpuconut--{
		go func() {
			for{
				select {
				case msg := <- ReceiveInfo_chan:
					ReceiveTypeMsg(msg)
					modul.GiveRecvinfo(msg)
				}
			}
		}()
	}
}

func Msg_deal_worker(data []byte){
	msg := modul.GetRecvinfo()
	err:=json.Unmarshal(data,msg)
	if wdlog.Error(err){
		return
	}
	//wdlog.Warning(string(data))
	switch msg.Message.MessageType{
	case 4: //群消息
		ReceiveTypeGroup(msg)
	case 3:
		//服务下线
		RecviveTypeRobotLeave(msg)
	case 2:
		ReceiveTypeMsg(msg)
		//ReceiveInfo_chan<-msg
	case 1:
		ReceiveTypeGroupInvite(msg)
	default:
	}
	//modul.GiveRecvinfo(msg)
}

//ReceiveTypeMsg 接受到信息类型为消息
func ReceiveTypeGroup(msg *modul.ReceiveInfo) {
	data_value, _ := json.Marshal(msg.Message.Data)
	data := modul.GetRecvdata()

	err := json.Unmarshal(data_value, data)
	if wdlog.Error(err) {
		return
	}
	if data.Category != 1 && data.Self {
		return
	}
	r := RobotList.First(data.ToUser)
	if r == nil {
		return
	}
	r.ReceiveTypeFour(data)
	return
}

//ReceiveTypeMsg 接受到信息类型为消息
func ReceiveTypeMsg(msg *modul.ReceiveInfo) {
	data_value, _ := json.Marshal(msg.Message.Data)
	data := modul.GetRecvdata()

	err := json.Unmarshal(data_value, data)
	if wdlog.Error(err) {
		return
	}
	if data.Category != 1 && data.Self {
		return
	}
	r := RobotList.First(data.ToUser)
	if r == nil {
		return
	}
	//wdlog.Warning(data)
	r.MsgPipe <- data
	return
	//if atomic.LoadInt32(&(r.MaxMsgList)) > conf.Global_Conf.MaxReceiveMsgCount{
	//	return
	//}else{
	//	r.MaxMsgList = atomic.AddInt32(&(r.MaxMsgList),1)
	//	defer func(){
	//		r.MaxMsgList = atomic.AddInt32(&(r.MaxMsgList),-1)
	//	}()
	//}
	wdlog.Debugln("接受到一条消息：",data.Type)
	switch data.Type {
	case 0: //文字
		plen := len(data.PushContent)
		if plen > 19 {
			if data.PushContent[(plen-19):] == "在群聊中@了你" {
				TextVerify(r, data)
				return
			}
		}
		if !authentication(r,data) {
			return
		}
		r.RangeWorkGroup(func(wcid string)bool {
			requests.SendText(r.Wid, wcid, data.Content, false)
			return true
		})
	case 1: //图片
		if !authentication(r,data) {
			return
		}
		//下载图片
		imgurl := requests.DownImage(r.Wid, data.Content, data.FromUser, data.ToUser, data.MsgId)
		if imgurl == "null" {
			return
		}
	    //转发图片
		r.RangeWorkGroup(func(wcid string)bool {
			requests.SendText(r.Wid, wcid, imgurl, true)
			return true
		})
	case 2: //视频
		if !authentication(r,data) {
			return
		}
		//leng := wdutil.RegexpFromStringS(data.Content,` thumbpath="(?s:(.*?))" `,1)
		//if len(leng) <1 {
		//	return
		//}
		//下载视频
		mvurl := requests.DownMV(r.Wid,data.Content,data.MsgId)
		if mvurl =="null"{
			return
		}
		//转发视频
		r.RangeWorkGroup(func(wcid string) bool{
			if err:= requests.SendMV(r.Wid, wcid, data.Content);wdlog.Error(err){
			}
			return true
		})
	case 3: //语音
		if !authentication(r,data) {
			return
		}
		leng := wdutil.RegexpFromStringS(data.Content,` voicelength="(?s:(.*?))" `,1)
		if len(leng) <1 {
			wdlog.Debugln("语音消息:","消息正则匹配失败")
			return
		}
		msglen,err:= strconv.ParseInt(leng[0][1],10,64)
		if wdlog.Error(err){
			return
		}
		viourl := requests.DownVoice(r.Wid,data.MsgId,msglen)
		if viourl =="null"{
			wdlog.Debugln("语音消息:","语音下载url为空")
			return
		}
		r.RangeWorkGroup(func(wcid string) bool{
			if err= requests.SendVoice(r.Wid,wcid,viourl,int(msglen));err!=nil{
				wdlog.Debugln(err)
			}
			return true
		})
	default:
		wdlog.Debugln("接受到一条其他类型信息:", data.Type)
	}
}
//ReceiveTypeGroupInvite 。。接受到的信息类型为群邀请
func ReceiveTypeGroupInvite(msg *modul.ReceiveInfo){
	//fmt.Println(msg)
	//wdlog.Warning(*msg)
}
//RecviveTypeRobotLeave 机器人下线
func RecviveTypeRobotLeave(msg *modul.ReceiveInfo){
	r := RobotList.First(msg.WCID)
	if r == nil {
		return
	}
	smodul.NewRecordAndInsert(r.ID,r.NickName,"null","机器人下线")
}


//authentication 过身份鉴权
func authentication(r * smodul.Robots,data * modul.ReceiveData)bool{
	if r.CurrentGroup != data.FromGroup{
		switch r.AddWorkGroup(data.FromGroup) {
		case 2:
			requests.SendText(r.Wid,data.FromGroup,"已为本群开启转播服务",false)
		case 3:
			requests.SendText(r.Wid,data.FromGroup,"转播群数已达上限，转播功能暂时不会关闭，请联系客服续费，微信：123456",false)
		}
		return false
	}
	if _,ok:=r.CurrentListWcid.Load(data.FromGroup);r.WorkStat == 2 && !ok{
		wdlog.Debugln("语音消息:","消息不符合主播身份")
		return false
	}else if r.CurrentGroup != data.FromGroup {
		return  false
	}
	if r.WorkProgress == 101{
		return false
	}
	return true
}

